/**
 * chenuu.com
 * 
 * @author  zhaoxu.com@gmail.com
 * @created 2012-11-18
 */
package com.chenuu.webapp.document.views;

import java.util.Date;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.chenuu.integration.dropbox.session.DefaultDropboxSession;
import com.chenuu.integration.dropbox.session.DropboxSession;
import com.chenuu.webapp.common.result.AjaxResult;
import com.chenuu.webapp.document.domain.DropboxFileGroup;
import com.chenuu.webapp.document.domain.DuplicateFiles;
import com.chenuu.webapp.document.service.DropboxService;
import com.dropbox.client2.exception.DropboxException;

/**
 *
 */
@Controller
public class DuplicateFilesView {

	protected Log logger = LogFactory.getLog(DuplicateFilesView.class);

	@Autowired
	private DropboxService dropboxService;

	@RequestMapping("/document")
	public String view() {
		return "/document/duplicate_files";
	}

	@RequestMapping("/document/duplicate_files/loadData.json")
	@ResponseBody
	public AjaxResult loadData(boolean searchDropbox) {

		AjaxResult result = new AjaxResult();

		DropboxSession session = this.getSession();
		if (session == null) {
			// TODO
		}
		try {
			DuplicateFiles duplicateFiles = dropboxService.findDuplicateFiles(session,
					searchDropbox);
			if (duplicateFiles == null) {
				result.setSuccess(false);
				result.setMessage("还没有您的扫描数据，请执行<a href='#' onclick=loadData(true)>立即扫描</a>。");
				if (logger.isDebugEnabled()) {
					logger.debug("没有扫描记录。");
				}
			} else {
				result.setSuccess(true);
				result.put("duplicateFiles", duplicateFiles);
				result.put("lastCheck", this.getLong(duplicateFiles.getLastCheck()));
				if (logger.isDebugEnabled()) {
					for (DropboxFileGroup group : duplicateFiles.getGroupList()) {
						logger.debug(group.getName());
					}
				}
			}
		} catch (DropboxException e) {
			// TODO
		}

		return result;
	}

	private DropboxSession getSession() {
		return new DefaultDropboxSession("0ii7jpj4p6x2wwm", "2pfi6q1ru2k0n9b");
	}

	private String getLong(Date lastCheck) {
		Date now = new Date();
		long diff = now.getTime() - lastCheck.getTime();

		long nd = 1000 * 24 * 60 * 60;// 一天的毫秒数  
		long nh = 1000 * 60 * 60;// 一小时的毫秒数  
		long nm = 1000 * 60;// 一分钟的毫秒数  
		long ns = 1000;// 一秒钟的毫秒数  

		long day = diff / nd;// 计算差多少天  
		long hour = diff % nd / nh;// 计算差多少小时  
		long min = diff % nd % nh / nm;// 计算差多少分钟  
		long sec = diff % nd % nh % nm / ns;// 计算差多少秒  

		String result;
		if (day > 0) {
			result = day + "天前";
		} else if (hour > 0) {
			result = hour + "小时前";
		} else if (min > 0) {
			result = min + "分钟前";
		} else {
			result = (sec > 0 ? sec : 1) + "秒前";
		}

		return result;
	}

}
